<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>10-阴影</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,
    body {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <script type="module">
    // 引入three.js
      import * as THREE from "three";
      import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

      //创建场景
      const scene = new THREE.Scene();

      //创建相机
      const camera = new THREE.PerspectiveCamera(
        45,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      //设置相机位置
      camera.position.set(0,100, 100); //统一设置
      //设置相机朝向点位
      camera.lookAt(0, 0, 0);

      //创建渲染器
      const renderer = new THREE.WebGLRenderer({
        antialias: true, //减少边缘齿轮
      });
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.shadowMap.enabled = true; //开启阴影投射
      document.body.appendChild(renderer.domElement);

      //光源
      const ambientLight = new THREE.AmbientLight( 0x404040,1 ); // 环境光
      scene.add(ambientLight)
      const directionalLight = new THREE.DirectionalLight(0xffffff,5) //平行光
      directionalLight.castShadow = true; //开启支持阴影投射
      directionalLight.shadow.mapSize.width = 2048 //阴影边线清晰度
      directionalLight.shadow.mapSize.height = 2048
      directionalLight.position.set(150,20,0) 
      const directionalHelper = new THREE.DirectionalLightHelper(
        directionalLight,5
      )
      scene.add(directionalLight,directionalHelper)

      const pointerLight = new THREE.PointLight(0xffffff,1000,100)
      pointerLight.position.set(30,30,0)
      pointerLight.castShadow = true
      const pointerLightHelper = new THREE.PointLightHelper(pointerLight,1)
      scene.add(pointerLight,pointerLightHelper)

      //创建结构-几何体
      const plane = new THREE.Mesh(
        new THREE.PlaneGeometry(100,100),
        new THREE.MeshStandardMaterial({
          color:0xffffff
        })
      )
      plane.rotation.x = -Math.PI / 2
      plane.receiveShadow = true //开启接受阴影
      scene.add(plane); //在场景中添加物体

      const cube = new THREE.Mesh(
        new THREE.BoxGeometry(20,20,20),
        new THREE.MeshStandardMaterial({color:0xff0000})
      )
      cube.position.set(0,10,0)
      cube.castShadow = true
      scene.add(cube)

      //控制插件
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true //开启惯性,需要和update方法配合使用

      let angle = 0
      //动画函数
      function animate() {
        angle+=0.01
        pointerLight.position.x = 30*Math.cos(angle)
        pointerLight.position.z = 30*Math.sin(angle)
        requestAnimationFrame(animate);
        controls.update()
        renderer.render(scene, camera);
      }
      animate();
    </script>
</body>

</html>